package com.fp.m7.server.auth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.fp.m7.dao.AccountDao;
import com.fp.m7.model.Account;

@Component("customAuthenticationProvider")
public class CustomAuthenticationProvider implements AuthenticationProvider {
    private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class);

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private M7PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        String username = (String) auth.getPrincipal();
        String password = (String) auth.getCredentials();

        Account account = accountDao.findByUsername(username);
        if (account == null) {
            String log = "No account found for username = [" + username + "]";
            logger.info(log);
            throw new UsernameNotFoundException(log);
        }

        if (password == null || !passwordEncoder.encodePassword(username, password).equals(account.getPassword())) {
            String log = "Invalid password for username = [" + username + "]";
            logger.info(log);
            throw new BadCredentialsException(log);
        }
        
        CustomAuthentication customAuth = new CustomAuthentication("ROLE_USER", auth);
        customAuth.setAuthenticated(true);
        
        return customAuth;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(clazz);
    }
    
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    
    public void setPasswordEncoder(M7PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

}
